package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"sync"
)

var wg sync.WaitGroup
var base = 16
var mod int

var (
	Elb           = "http://io-private-c2932aec8eab3926.elb.ap-northeast-1.amazonaws.com"
	WebConsoleUrl = fmt.Sprintf("%s:21010/api/get_config?platform=0", Elb)
)

type Markets struct {
	FeeCoin        string `json:"fee_coin"`
	FeePrec        int    `json:"fee_prec"`
	Id             int    `json:"id"`
	MinAmount      string `json:"min_amount"`
	Money          string `json:"money"`
	MoneyPrec      int    `json:"money_prec"`
	Name           string `json:"name"`
	SpecialFeeFlag int    `json:"special_fee_flag"`
	Status         int    `json:"status"`
	Stock          string `json:"stock"`
	StockPrec      int    `json:"stock_prec"`
	Type           int    `json:"type"`
}

type Content struct {
	Assets  []map[string]interface{} `json:"assets"`
	Markets []Markets                `json:"markets"`
}

type CoinList struct {
	Content Content `json:"Content"`
}

type HttpResponse struct {
	Error  error       `json:"error"`
	Result interface{} `json:"result"`
	Id     int64       `json:"id"`
}

func GetCoinIdAndName(w http.ResponseWriter, r *http.Request) {
	res, err := http.Get(WebConsoleUrl)
	if err != nil {
		panic(err)
	}

	body, err := io.ReadAll(res.Body)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var conlist CoinList
	err = json.Unmarshal(body, &conlist)
	if err != nil {
		log.Println(err)
	}

	marketlists := conlist.Content.Markets
	pool := make(chan string, 65536)
	for _, content := range marketlists {
		wg.Add(1)
		go CheckMod(content.Id, content.Name, pool)
	}
	wg.Wait()

	var result string
	wg.Add(1)
	go func() {
		defer wg.Done()
		for {
			select {
			case msg := <-pool:
				result += fmt.Sprintf("%s", msg)
				if len(pool) == 0 {
					return
				}
			default:
				return
			}
		}
	}()
	wg.Wait()
	fmt.Fprintf(w, "%s", result)
}

func CheckMod(id int, name string, msg chan string) {
	defer wg.Done()
	mod = id % base

	HttpServerUrl := fmt.Sprintf("%s:22681/v2/p1/order.depth?market=%s&limit=10&interval=0.00000001", Elb, name)
	resp, err := http.Get(HttpServerUrl)
	if err != nil {
		log.Println(err)
		return
	}
	defer resp.Body.Close()
	body, _ := io.ReadAll(resp.Body)
	httpResp := HttpResponse{
		Error:  nil,
		Result: nil,
		Id:     0,
	}
	err = json.Unmarshal(body, &httpResp)
	if err != nil {
		log.Println(err)
	} else if httpResp.Error != nil {
		if mod == 0 {
			msg <- fmt.Sprintf("%s config%d, ", name, mod)
		} else {
			msg <- fmt.Sprintf("%s config%d, ", name, mod+2)
		}
	}
}

func main() {
	http.HandleFunc("/", GetCoinIdAndName)
	err := http.ListenAndServe(":17576", nil)
	if err != nil {
		panic(err)
	}
}
